package com.example.ai.mapper;

import com.example.ai.entity.ChatMessage;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface ChatMessageMapper {

    void insertMessage(ChatMessage message);

    @Select("SELECT content, create_time FROM chat_message " +
            "WHERE user_id = #{userId} " +
            "ORDER BY create_time DESC " +
            "LIMIT #{limit}")
    List<ChatMessage> selectRecentMessages(
            @Param("userId") String userId,
            @Param("limit") int limit
    );

    @Delete("DELETE FROM chat_message " +
            "WHERE user_id = #{userId} " +
            "AND create_time < #{threshold}")
    int deleteOldMessages(
            @Param("userId") String userId,
            @Param("threshold") LocalDateTime threshold
    );

    @Delete({
            "<script>",
            "DELETE FROM chat_message",
            "WHERE user_id = #{userId}",
            "<if test='excludeIds != null and excludeIds.size() > 0'>",
            "AND id NOT IN",
            "<foreach item='id' collection='excludeIds' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</if>",
            "</script>"
    })
    int deleteByUserIdExcludingIds(
            @Param("userId") String userId,
            @Param("excludeIds") List<Long> excludeIds
    );

    @Insert({
            "<script>",
            "INSERT INTO chat_message (user_id, content, create_time) VALUES ",
            "<foreach item='item' collection='list' separator=','>",
            "(#{item.userId}, #{item.content, typeHandler=...}, #{item.createTime})",
            "</foreach>",
            "</script>"
    })
    void batchInsert(@Param("list") List<ChatMessage> messages);
}
